package com.jhc.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jhc.dto.BizRoleSearchUserByRoleDto;
import com.jhc.dto.CmsRoleAdd;
import com.jhc.dto.CmsRoleDelete;
import com.jhc.dto.CmsRoleUpdate;
import com.jhc.entity.CmsRole;
import com.jhc.entity.UserAuthData;
import com.jhc.service.ICmsRoleService;
import com.jhc.utils.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * cms_role  前端控制器
 * </p>
 *
 * @author zfm
 * @since 2019-11-24
 */
@RestController
@RequestMapping("/role")
@Api(tags = "用户 角色管理")
public class CmsRoleController {

    @Autowired
    private ICmsRoleService cmsRoleService;

    @ApiOperation("添加角色role:add")
    @PostMapping()
    @PreAuthorize("hasAuthority('role:add')")
    public CommonResult addRole(@Validated @RequestBody CmsRoleAdd cmsRoleAdd) {
        CmsRole cmsRole = new CmsRole();
        if (cmsRoleService.getOne(new QueryWrapper<CmsRole>().lambda()
                .eq(CmsRole::getName, cmsRoleAdd.getName())) != null) {
            return CommonResult.failed("权限名称重复！");
        }
        BeanUtils.copyProperties(cmsRoleAdd, cmsRole);
        if (cmsRoleAdd.getAuthDataList().size() != 0) {
            UserAuthData userAuthData = new UserAuthData();
            userAuthData.setAuthList(cmsRoleAdd.getAuthDataList());
            cmsRole.setAuthData(JSONUtil.toJsonStr(userAuthData));
        } else {
            cmsRole.setAuthData("{}");
        }
        if (cmsRoleService.save(cmsRole)) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("服务器异常");
    }

    @ApiOperation("删除角色role:delete")
    @DeleteMapping()
    @PreAuthorize("hasAuthority('role:delete')")
    public CommonResult deleteRole(@Validated @RequestBody CmsRoleDelete cmsRoleDelete) {
        if (cmsRoleService.removeByIds(cmsRoleDelete.getRoleIdList())) {
            return CommonResult.success("删除成功");
        } else {
            return CommonResult.failed("删除失败");
        }
    }

    @ApiOperation("更新角色role:update")
    @PutMapping()
    @PreAuthorize("hasAnyAuthority('role:update')")
    public CommonResult updateRole(@Validated @RequestBody CmsRoleUpdate cmsRoleUpdate) throws InterruptedException {
        CmsRole cmsRole = new CmsRole();
        BeanUtils.copyProperties(cmsRoleUpdate, cmsRole);
        UserAuthData userAuthData = new UserAuthData();
        userAuthData.setAuthList(cmsRoleUpdate.getAuthDataList());
        cmsRole.setAuthData(JSONUtil.toJsonStr(userAuthData));
        if (cmsRoleService.getOne(new QueryWrapper<CmsRole>().lambda().
                eq(CmsRole::getName, cmsRole.getName()).ne(CmsRole::getId, cmsRoleUpdate.getId())) != null) {
            return CommonResult.failed("角色名称已被使用");
        }
        if (cmsRoleService.updateById(cmsRole)) {
            cmsRoleService.updateRole(cmsRoleUpdate);
            return CommonResult.success("更新成功");
        } else {
            return CommonResult.failed("更新失败");
        }
    }

    @ApiOperation("查询角色role:search")
    @GetMapping()
    @PreAuthorize("hasAnyAuthority('role:search')")
    public CommonResult search(
            @RequestParam(value = "pageSize", defaultValue = "1") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "5") Integer pageNum,
            @RequestParam(value = "name", defaultValue = "") String name
    ) {
        IPage<CmsRole> page = new Page<>(pageNum, pageSize);
        QueryWrapper<CmsRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(CmsRole::getName, name);
        return CommonResult.success(cmsRoleService.page(page, queryWrapper));
    }

    @ApiOperation("根据角色查询权限 树形状role:search:permission")
    @GetMapping("/{roleId}")
    @PreAuthorize("hasAuthority('role:search:permission')")
    public CommonResult searchByRoleId(@PathVariable(name = "roleId") Long id) {
        return CommonResult.success(cmsRoleService.getPermissionList(id));
    }

    @ApiOperation("根据角色查询用户")
    @GetMapping("/teacher")
    public CommonResult searchUserByRoleId(@Validated BizRoleSearchUserByRoleDto bizRoleSearchUserByRoleDto) {
        return CommonResult.success(cmsRoleService.getUserByRoleInfo(bizRoleSearchUserByRoleDto));
    }

}
